package com.wangbo.validate;

import com.wangbo.validate.model.param.UserAdd;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import java.util.Set;

@Validated
@RestController
public class TestController {

    @Resource
    public Validator validator;

    @PostMapping("/user")
    public void addUser(@RequestBody @Validated UserAdd userAdd) {
        System.out.println(userAdd);
    }

    @GetMapping("/user")
    public void getUser(@NotNull(message = "用户ID不能为空") @Min(value = 0L) Integer id) {
        System.out.printf("id=%d%n", id);
    }

    /**
     * 编程式校验
     */
    @GetMapping("/user/manual")
    public void manualValidate() {
        UserAdd userAdd = new UserAdd()
                .setName("张三");
        Set<ConstraintViolation<UserAdd>> validate = validator.validate(userAdd, Default.class);
        if (validate.isEmpty()) {

        } else {
            for (ConstraintViolation<UserAdd> userAddConstraintViolation : validate) {
                System.out.println(userAddConstraintViolation);
            }
            // ConstraintViolationImpl{interpolatedMessage='租户ID不能为空', propertyPath=tenantId, rootBeanClass=class com.wangbo.validate.model.param.UserAdd, messageTemplate='租户ID不能为空'}
            // ConstraintViolationImpl{interpolatedMessage='电话号码不能为空', propertyPath=phone, rootBeanClass=class com.wangbo.validate.model.param.UserAdd, messageTemplate='电话号码不能为空'}
        }
    }

}
